package com.yzc.service.Impl;

import com.yzc.apis.logClient.MainOrderLogClient;
import com.yzc.execption.ZcException;
import com.yzc.model.entity.log.OrderStatusLog;
import com.yzc.model.entity.ticket_order.OrderMain;
import com.yzc.rabbit.OrderStatus;
import com.yzc.result.ResultCodeEnum;
import com.yzc.util.AuthContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.Date;
import java.util.Set;

@Slf4j
@Service
@RequiredArgsConstructor
public class logPaymentServiceImpl {

    private final MainOrderLogClient mainOrderLogClient;


    private String getUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            return authentication.getName();
        }
        return "system"; // 默认值，根据业务需求调整
    }

    @Async
    public void logPaymentResult(Long orderId, OrderMain order, Integer orderStatus, String remark, HttpServletRequest request) {
        try {

            String authorizationHeader = request.getHeader("Authorization");


            OrderStatusLog orderLog = new OrderStatusLog();
            orderLog.setOrderId(orderId);
            orderLog.setStatus(orderStatus);
            orderLog.setOperator(getUsername() + ":" + order.getUserId());
            orderLog.setRemark(remark + "，支付金额: " + order.getTotalAmount());
            orderLog.setCreateTime(new Date());

            // 保存日志
            mainOrderLogClient.createOrderLog(orderLog, authorizationHeader);
            log.info("记录支付结果日志，订单ID: {}，支付结果: {}", orderId, orderStatus);

            if (orderStatus == OrderStatus.status_PAID.getCode()) {
                log.info("订单支付成功，订单ID: {}", orderId);
            } else {
                log.error("订单支付失败，订单ID: {}", orderId);
            }
        } catch (Exception e) {
            log.error("数据为:{}", order);
            log.error("logPaymentServiceImpl----记录支付结果日志失败，订单ID: {}", orderId, e);
            throw new ZcException(ResultCodeEnum.FAIL.getCode(), "记录支付结果日志失败");
        }finally {
            // 清理请求上下文
            RequestContextHolder.resetRequestAttributes();
        }
    }


}
